package com.example.jsoup;

import com.example.core.WebItemsCrawler;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class JavdbPageListCrawler extends WebItemsCrawler<JavdbRow> {
    private static final String XPATH = "//div[@class='item']";

    private String actorCn;
    private String actorJp;
    private List<String> actorAlias = new ArrayList<>();

    public JavdbPageListCrawler(String url) throws IOException {
        super(url, XPATH);
    }

    @Override
    protected void init() {
        if (actorCn != null) {
            return;
        }
        String actorNames = Optional.of(doc.selectXpath("//span[@class='actor-section-name']")).map(Elements::first).map(Element::text).orElse("");
        String[] names = actorNames.split(", ");
        if (names.length == 0) {
            return;
        }
        this.actorCn = names[0];
        if (names.length == 2) {
            this.actorJp = names[1];
        }
        String alias = Optional.of(doc.selectXpath("//span[@class='section-meta']")).map(Elements::first).map(Element::text).orElse("");
        if (alias.isBlank()) {
            return;
        }
        String[] aliases = alias.split(", ");
        for (String item : aliases) {
            this.actorAlias.add(item.trim());
        }
    }

    @Override
    protected JavdbRow parseItem(Element element) {
        Element item = element.child(0);
        String id = getByClassFirst(item, "video-title").map(x -> x.child(0)).map(Element::text).orElse("");
        String url = element.attr("href");
        String title = getByClassFirst(item, "video-title").map(Element::text).orElse("");
        String date = getByClassFirst(item, "meta").map(Element::text).orElse("");
        String otherTag = Optional.ofNullable(element.children().last()).map(Element::text).orElse("");

        JavdbRow row = new JavdbRow();
        row.setId(id);
        row.setActorCn(actorCn);
        row.setActorJp(actorJp);
        row.setActorAlias(actorAlias);
        row.setUrl(url);
        row.setTitle(title);
        row.setDate(date);
        row.setOtherTag(otherTag);
        return row;
    }

    private Optional<Element> getByClassFirst(Element item, String className) {
        return Optional.of(item.getElementsByClass(className)).map(Elements::first);
    }
}
